import { h, ref, watch, onMounted, onUnmounted } from "vue";

const CanvasVideo = {
  name: "CanvasVideo",
  props: {
    src: { default: "" },
  },
  setup(props, { attrs }) {
    let canvas = ref(null);
    let canvasEl, video, play, ctx, animateFrame;
    video = document.createElement("video");
    video.muted = true;
    video.autoplay = true;
    video.loop = attrs.loop === true;
    onMounted(() => {
      canvasEl = canvas.value;
      canvasEl.width = canvasEl.clientWidth;
      canvasEl.height = canvasEl.clientHeight;
      watch(
        () => props,
        ({ src }) => {
          video.oncanplay = async () => {
            await video.play();
            ctx = canvasEl.getContext("2d");
            play = function () {
              if (ctx) {
                ctx.drawImage(video, 0, 0, canvasEl.width, canvasEl.height);
                animateFrame = window.requestAnimationFrame(play);
              }
            };
            play();
          };
          if (!video.loop) {
            video.onended = () => {
              window.cancelAnimationFrame(animateFrame);
              video.pause();
            };
          }
          video.src = src;
          video.load();
        },
        { immediate: true }
      );
    });
    onUnmounted(() => {
      window.cancelAnimationFrame(animateFrame);
      video.pause();
      animateFrame = null;
      canvasEl = null;
      canvas = null;
      video = null;
      play = null;
      ctx = null;
    });
    return { canvasProps: { ref: canvas } };
  },
  render() {
    return h(
      "canvas",
      Object.assign({}, this.$attrs, this.canvasProps),
      "当前浏览器版本过低,请升级最新Chrome浏览器!"
    );
  },
};

export default CanvasVideo;
